<template>
  <div class="food-card">
    <img :src="image" :alt="name" class="food-image">
    <div class="food-info">
      <h3>{{ name }}</h3>
      <p class="price">¥{{ price.toFixed(2) }}</p>
      <p v-if="description" class="description">{{ description }}</p>
    </div>
    <button
      @click="addToCart"
      :disabled="isInCart"
      :class="{ 'in-cart': isInCart }"
    >
      {{ isInCart ? '已添加' : '加入购物车' }}
    </button>
  </div>
</template>

<script>
import { useCartStore } from '../utils/cart.js'
import { computed } from 'vue'

export default {
  props: {
    id: {
      type: [Number, String],
      required: true
    },
    name: {
      type: String,
      required: true
    },
    price: {
      type: Number,
      required: true
    },
    image: {
      type: String,
      default: '/placeholder-food.jpg'
    },
    description: {
      type: String,
      default: ''
    }
  },

  setup(props) {
    const cart = useCartStore()

    // 检查商品是否已在购物车
    const isInCart = computed(() => {
      return cart.items.some(item => item.id === props.id)
    })

    // 添加到购物车方法
    const addToCart = () => {
      cart.addItem({
        id: props.id,
        name: props.name,
        price: props.price,
        image: props.image
      })
    }

    return {
      cart,
      isInCart,
      addToCart
    }
  }
}
</script>

<style scoped>
.food-card {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 16px;
  max-width: 250px;
}

.food-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  margin: 8px 0;
}

.description {
  color: #666;
  font-size: 0.9em;
  margin-bottom: 12px;
}

button {
  background: #42b983;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

button:hover:not(.in-cart) {
  background: #3aa876;
}

.in-cart {
  background: #ccc;
  cursor: not-allowed;
}
</style>